<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .title {
            font-size: 30px;
        }
        body{
            width:100%;
            height:100%;
            background-color:yellow;
        }
        #myDiv{
            background-color:red;
        }
    </style>
</head>
<body>
<div class="title">h5页面</div>
<button onclick="sendMessage()">发送消息给原生</button>
<div id="myDiv"></div>
</body>
</html>
<script>
    //需要接受端口
    var currentPort
    window.addEventListener("message",()=>{
        if(event.data=="trans_port"){
            currentPort = event.ports[0]
            //接受鸿蒙端发送的消息
            currentPort.onmessage=(event)=>{
               document.querySelector("#myDiv").innerText = event.data
         }
    })


    function sendMessage(){

        if(currentPort){
            var obj = {"type":"alert","message":"我是网页中获取的数据"}
            //通过网页端端口发送数据给鸿蒙端
            currentPort.postmessage(JSON.stringify(obj))
        } 
    }
</script>